<?php
namespace app\manage\controller;
use app\common\model\ClueErrorLog;
use app\lib\exception\ParamException;
use other\MessageSend;
use other\SmsBCSend;
use other\SmsMuSend;
use other\SmsWYSend;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Config;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Exception;
use think\Log;
use think\Queue;

class Test extends Controller
{
    public function clue_export(){

        $redis=redis();
        dump($redis);
//        $redis->incr('wuhannum');
        dump($redis->incr('wuhannum'));

        dump($redis->get('wuhannum'));


        if($redis->get('wuhannum')%2==0){
            $type='1';
        }else{
            $type='2';
        }
        dump($type);die;






        //让程序一直运行
        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '128M');
        //(new \app\common\controller\Export())->clue();
    }

    public function isNull(){


        $isDayPhone = model('clue')->where(['phone' => '17260378963'])->whereTime('create_time','d')->find();
        dump($isDayPhone);die;

        Db::name('merchant')->where('id', 382)->dec('balance', 1500)->dec('balance2',1500)->update();
        die;



        $dateTime=date('Y-m-d');
        $dday=date('Y-m-d',strtotime('-3 days',strtotime($dateTime)));
        echo $dday;die;

        $isDayPhone = model('clue')->where(['phone' =>'15922583788'])->whereTime('create_time','d')->find();
        dump($isDayPhone);die;
    }
    public function getCityName($id)
    {


        $city = Db::name('city')->where(['id'=>$id])->find();
        return $city['name'];
    }

    public function allCityClueExport(){
        $type=input('get.type');
        $mer_id=input('get.mer_id');


        $map=[];
        if(!empty($mer_id)){
            $map['mer_id']=$mer_id;
        }

        if($type==1){
            $infos=Db::name('clue_log')->field('city,sum(price) price,count(id) num')->where($map)->group('city')->select();
            $name = '当前库城市线索金额';
        }else{
            $db=config('database')['backup_dbhost'];
            $infos=Db::connect($db)->name('wy_clue_log')->field('city,sum(price) price,count(id) num')->where($map)->group('city')->select();
            $name = '备份库城市线索金额';
        }

//        $db=config('database')['backup_dbhost'];
//        $res=Db::connect($db)->name('wy_clue_log')->field('city,sum(price) price')->group('city')->select();
//
//        $log=[];
        foreach ($infos as &$v){
            if($v['city'] != ''){
                $ids = explode('-',$v['city']);
                $cityNum=count($ids);
                if($cityNum==1){
                    $v['citycn'] = $this->getCityName($ids[0]);
                }elseif ($cityNum==2){
                    $prov = $this->getCityName($ids[0]);
                    $city = $this->getCityName($ids[1]);
                    if($prov == $city){
                        $v['citycn'] = $prov;
                    }else{
                        $v['citycn'] = $prov.'-'.$city;
                    }
                }
            }else{
                $v['citycn'] = '无';
            }
        }

        $newExcel = new Spreadsheet();
//获取当前操作sheet的对象
        $objSheet = $newExcel->getActiveSheet();
        $date = date('Ymd',time());
//        $name = '当前库城市线索金额';
        $objSheet->setTitle($name);//设置当前sheet的标题
//设置表头


            $objSheet->setCellValue('A1', '城市id')
                ->setCellValue('B1', '金额')
                ->setCellValue('C1', '数量')
                ->setCellValue('D1', '城市')
            ;


            $objSheet->getColumnDimension('A')->setWidth(20);
            $objSheet->getColumnDimension('B')->setWidth(15);
            $objSheet->getColumnDimension('C')->setWidth(10);
            $objSheet->getColumnDimension('D')->setWidth(20);


            $info = $infos;
//            dump($info);die;
            $dataCount = count($info);
            $k = 1;
            if($dataCount == 0){
                exit;
            }else {
                for ($i = 0; $i < $dataCount; $i++) {
                    $k = $k + 1;
                    $objSheet->setCellValue('A' . $k, $info[$i]['city'])
                        ->setCellValue('B' . $k, $info[$i]['price'])
                        ->setCellValue('C' . $k, $info[$i]['num'])
                        ->setCellValue('D' . $k, $info[$i]['citycn'])
                    ;
                }
            }



        $filename = date('Y-m-d').$name;
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename='.$filename.'.xlsx');
        header('Cache-Control: max-age=0');
//
        $write = IOFactory::createWriter($newExcel, 'Xlsx');
        $write->save('php://output');

    }


    public function smssend(){

//        echo 'aaa我靠';
//        $mobiles='15922583788';
        $mobiles='15950842938';
//        $content='【'.config('database')['host_sms_name'].'】提醒你有个线索查看！';
//        $extno='';
//        $sendtime='';
//        $res=MessageSend::send($mobiles,$extno,$content,$sendtime);
//        dump($res);

//        $mobiles = $sendPhone;
        $content = '【'.config('database')['host_sms_name'].'】提醒你有个线索查看！';
//        $content = '【'.config('database')['host_sms_name'].'】渠道：测试，城市：复杂-订单，失败原因：传达时代发大水发大水';
        $extno = '';
        $sendtime = '';
//        $sendRes = MessageSend::send($mobiles, $extno, $content, $sendtime);
                    $res=SmsMuSend::send($mobiles,$content);
                    dump($res);


    }


    public function testxxx(){

        $times='2024-1-23';

        $timeStar=strtotime($times.' 00:00:00');
        $timeEnd=strtotime($times.' 23:59:59');

        $map['create_time'] = ['between',[$timeStar,$timeEnd]];

        $jobHandlerClassName  = 'app\job\CluePriceAdmin@fire';
        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
        $jobQueueName     = "CluePriceAdmin";

        $jobData = ['time'=>$map['create_time']];

        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
    }

    public function updateShopFzMoney(){
        $m=Db::name('merchant')->column('id');
        foreach ($m as $v){
            $zmoney=Db::name('charge')->where('mer_id',$v)->sum('fz_money');
            $xiaohao=Db::name('clue_log')->where('mer_id',$v)->sum('price');
            $money=bcsub($zmoney,$xiaohao,2);
            Db::name('merchant')->where('id',$v)->update(['balance2'=>$money]);
            echo 1;
        }
    }



    public function changeShopStatus(){
        $list=Db::name('merchant_copy1')->where('status',1)->column('id');
        Db::name('merchant')->whereIn('id',$list)->update(['status'=>1]);
        echo 1;
    }

    //数据库备份
    public function backups()
    {

        echo '【'.config('database')['host_sms_name'].'】提醒你有个线索查看！';
        die;


        //1.获取数据库信息
        $info = config('database');
        $dbname = $info['database'];
        //2.获取数据库所有表
        $tables = Db::query("show tables");
        //3、组装头部信息
        header("Content-type:text/html;charset=utf-8");
        $path = './data/';
        $database = $dbname;   //获取当前数据库
        $info  = "-- ----------------------------\r\n";
        $info .= "-- 日期：".date("Y-m-d H:i:s",time())."\r\n";
        $info .= "-- MySQL - 5.7-MariaDB : Database - ".$database."\r\n";
        $info .= "-- ----------------------------\r\n\r\n";
        $info .= "SET NAMES utf8;\r\nSET FOREIGN_KEY_CHECKS = 0;\r\n\r\n";
        //4、检查目录是否存在
        if (is_dir($path)) {
            if (is_writable($path)) {
            } else {
                echo '目录不可写'; exit();
            }
        } else {
            mkdir($path,0777,true);
        }
        //5、保存的文件名称
        $file_name = $path.$database.'_'.date('Ymd_His').'.sql';
        file_put_contents($file_name, $info, FILE_APPEND);
        //6、循环表，写入数据
        foreach ($tables as $k => $v) {
            $val = $v["Tables_in_$database"];
            $sql = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='$val' AND TABLE_SCHEMA='$dbname'";
//            $sql = "SELECT * FROM ".$val;
            $res = Db::query($sql);
            $tableStatus = Db::query("SHOW TABLE STATUS FROM `{$res[0]['TABLE_SCHEMA']}` WHERE name = '{$res[0]['TABLE_NAME']}'");
            $eng = strtolower($tableStatus[0]['Engine']);

            //查询表结构
            $info_table = "-- ----------------------------\r\n";
            $info_table .= "-- Table structure for `$val`\r\n";
            $info_table .= "-- ----------------------------\r\n\r\n";
            $info_table .= "DROP TABLE IF EXISTS `$val`;\r\n";
            if (count($res) < 1) {
                continue;
            }
            $info_table .= "CREATE TABLE `$val` (\n\r\t";
            foreach ($res as $kk => $vv) {
                $info_table .= " `".$vv['COLUMN_NAME']."` ";
                $info_table .= $vv['COLUMN_TYPE'];
                //是否允许空值
                if ($vv['IS_NULLABLE'] == 'NO') {
                    $info_table .= " NOT NULL ";
                }
                //判断主键
                if ($vv['EXTRA']) {
                    $info_table .= " AUTO_INCREMENT ";
                    $key = $vv['COLUMN_NAME'];
                }
                //编码
//                if ($vv['CHARACTER_SET_NAME']) {
//                    $info_table .= " CHARACTER SET ".$vv['CHARACTER_SET_NAME'];
//                }
                //字符集
                if ($vv['COLLATION_NAME']) {
                    $info_table .= " COLLATE ".$vv['COLLATION_NAME'];
                }
                //默认数值
                if ($vv['COLUMN_DEFAULT']) {
                    $info_table .= " DEFAULT ".$vv['COLUMN_DEFAULT'];
                }
                //注释
                if ($vv['COLUMN_COMMENT']) {
                    $info_table .= " COMMENT '".$vv['COLUMN_COMMENT']."',\n\r\t";
                }else{
                    $info_table .= ",\n\r\t";
                }
            }
            $info_table .= " PRIMARY KEY (`$key`) USING BTREE";
            $info_table .= "\n\r) ENGINE={$eng} AUTO_INCREMENT=212 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;\r\n\r\n";

            //查询表数据
            $info_table .= "-- ----------------------------\r\n";
            $info_table .= "-- Data for the table `$val`\r\n";
            $info_table .= "-- ----------------------------\r\n\r\n";
            file_put_contents($file_name,$info_table,FILE_APPEND);
            $sql_data = "select * from $val";
            $data = Db::query($sql_data);
            $count= count($data);
            if ($count < 1) {
                continue;
            }
            foreach ($data as $key => $value) {
                $sqlStr = "INSERT INTO `$val` VALUES (";
                foreach($value as $v_d){
                    $v_d = str_replace("'","\'",$v_d);
                    $sqlStr .= "'".$v_d."', ";
                }
                //需要特别注意对数据的单引号进行转义处理
                //去掉最后一个逗号和空格
                $sqlStr = substr($sqlStr,0,strlen($sqlStr)-2);
                $sqlStr .= ");\r\n";
                file_put_contents($file_name,$sqlStr,FILE_APPEND);
            }
            $info = "\r\n";
            file_put_contents($file_name,$info,FILE_APPEND);
        }


        $zip = new \ZipArchive();
        $zipName = $path.'backup_' . date('Y-m-d_H-i-s') . '.zip';

        if ($zip->open($zipName, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === true) {
            // 备份数据库文件的代码将在这里添加
            $zip->addFile($file_name);
            $zip->close();
        } else {
            exit('无法打开压缩包文件');
        }



        //7、下载数据到本地
        ob_end_clean();
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Length: ' . filesize($zipName));
        header('Content-Disposition: attachment; filename=' . basename($zipName));
        readfile($zipName);
//        DownloadFile($path.$file_name);
        echo "数据已备份";
        exit;
    }

    public function isGengJin(){

        $city=Db::name('city')->where('remark','<>','')->select();
        dump($city);die;

//        Db::name('clue_log')->where('progress_status','>',0)->whereOr('level_status','>',0)->update(['is_follow'=>1]);
//        $cId=Db::name('clue_progress')->column('clue_log_id');
//        Db::name('clue_log')->whereIn('id',$cId)->update(['is_follow'=>1]);

        $db=config('database')['backup_dbhost'];
//        dump($db);die;
        $aaa=1;
        $bbb=2;
        $all=Db::name('clue')->where('status',1)->chunk(100, function($dbData) use ($aaa,$bbb) {
            dump($aaa);
            dump($bbb);
            foreach ($dbData as $v){
//                dump($v);

            }
        });
        dump($all);die;

        $res=Db::connect($db)->name('wy_admin')->select();
        dump($res);

        dump(config('ts_mer_id'));

    }

    public function getconfig(){

        $pushs = model('Push')->getListByMap(['pro_id' => 4, 'city' => '14-197']);
        dump($pushs);

        $listPush=[426];

        foreach ($pushs as $k => $v) {
            $isC=false;
            foreach ($listPush as $vv){
                if($v['id']==$vv){
                    unset($pushs[$k]);
                    $isC=true;
                }
            }
            if($isC){
                continue;
            }
            dump($v);
        }

        dump($pushs);die;



        dump(Config::get('queue'));
    }
    public function week(){
        $list=Db::name('push')->select();
        foreach ($list as $v){
            if(!empty($v['week_time'])){
                $timing_time=json_decode($v['week_time'],true);

                if(!empty($timing_time)){
                    if(isset($timing_time[10])){

                    }else{
                        $save_data['week_day']=implode(',',array_keys($timing_time));
                        Db::name('push')->where('id',$v['id'])->update($save_data);
                        echo 1;
                    }
                }
            }
        }
    }

    public function pushTImeBatch(){
        $list=Db::name('push')->select();
        foreach ($list as $v){
            if(!empty($v['timing_time'])){
                $timing_time=explode(' - ',$v['timing_time']);
                $save_data['start_time']=$timing_time[0];
                $save_data['end_time']=$timing_time[1];
                Db::name('push')->where('id',$v['id'])->update($save_data);
                echo 1;
            }
        }
    }

    //映射投放时间
    public function merPushTime(){
        $mer=Db::name('merchant')->select();
        foreach ($mer as $v){
            $saveData=['start_time'=>$v['start_time'],'end_time'=>$v['end_time'],'timing_time'=>$v['timing']];
            if(empty($v['weekday'])){
                if(!empty($v['timeday'])){
                    $saveData['week_time']=json_encode([
                        10=>$v['timeday']
                    ]);
                }
            }else{
                $week=explode(',',$v['weekday']);
                $weekArr=[];
                foreach ($week as $vv){
                    $weekArr[$vv]=$v['timeday'];
                }
                $saveData['week_time']=json_encode($weekArr);
            }
            Db::name('push')->where('mer_id',$v['id'])->update($saveData);
            echo 1;
        }
    }


    public function pushTypeBatch(){
        $push=Db::name('push')->where('type',1)->select();
        foreach ($push as $v){
            $saveData['type']=2;
            if(empty($v['channel_id'])){
                $saveData['account_id']=0;
            }else{
                $channelArr=explode(',',$v['channel_id']);
                foreach ($channelArr as $vv){
                    $accountArr=model('account')->where('channel_id',$vv)->column('id');
                    $saveData['account_id']=implode(',',$accountArr);
                }
            }
            Db::name('push')->where('id',$v['id'])->update($saveData);
            echo 1;
        }
    }
    public function accountBatchClue(){
        $account=Db::name('account')->select();
        foreach ($account as $v){
            Db::name('clue')->where('adv_id',$v['adv_id'])->update(['account_id'=>$v['id']]);
            echo 1;
        }
    }


    public function index()
    {
        Log::error('------------aaaaa---------');
    }

    public function look()
    {
        echo cookie('think_auth');
    }

    public function quit()
    {
        cookie('think_auth',null);
    }

    public function accept()
    {

        $post = file_get_contents("php://input");
//        Log::record($post, 'error');
//        Log::record($_GET, 'error');

        $type = 3;
        $post = '{"cid": 0, "phone": "18727483224", "adv_id": "1797273009934356", "gender": "未知", "req_id": "20240428152749697B767013A149704FAB", "address": "420100", "clue_id": "7362818565067505702", "site_id": "7361730762305536010", "adv_name": "车丫丫-东莞", "app_name": "字节-抖音", "location": "湖北+孝感", "mid_info": "{\"titleId\":7362053660806774793,\"videoId\":7319345018358497317}", "store_id": 0, "clue_type": 0, "flow_type": 4, "module_id": "1797302915589179", "site_name": "车主服务", "clue_source": 1, "create_time": "1714289782", "module_name": "车", "remark_dict": {"所需额度": "10-15万", "车辆类型": "按揭车接受押车", "裸车购买价": "10-20万", "汽车品牌与型号": "广汽埃安Y—LNADKAB12P1082946"}, "external_url": "https://www.chengzijianzhan.com/tetris/page/7361730762305536010/", "promotion_id": 7362053604417290267, "province_name": "湖北", "store_pack_id": 0, "promotion_name": "0426-车丫丫-1", "clue_convert_status": "合法转化"}';

        $params = json_decode($post, true);

        $clueName=isset($params['clue_name']) ? $params['clue_name'] : '';
        if(empty($clueName)&&$type==1){
            $clueName=isset($params['name']) ? $params['name'] : '';
        }

        $insertLog = [
            'adv_id' => isset($params['adv_id']) ? $params['adv_id'] : '',
            'phone' => isset($params['phone']) ? $params['phone'] : '',
            'name' => $clueName,
            'city' => isset($params['city']) ? $params['city'] : '',
            'param' => json_encode($_GET, JSON_UNESCAPED_UNICODE),
            'data' => json_encode($params, JSON_UNESCAPED_UNICODE),
            'create_time' => date('Y-m-d H:i:s')
        ];
        if ($type == 1) {
            $apiType = '百度';
            $insertLog['adv_id'] = isset($params['ucid']) ? $params['ucid'] : '';
        } elseif ($type == 2) {
            $apiType = '腾讯';
            $insertLog['adv_id'] = isset($params['adv_id']) ? $params['adv_id'] : '';
        } elseif ($type == 3) {
            $apiType = '抖音';
            $insertLog['adv_id'] = isset($params['adv_id']) ? $params['adv_id'] : '';
        } else {
            $apiType = $type;
        }
        $insertLog['api_url'] = $apiType;
        $apiId=Db::name('clue_api_log')->insertGetId($insertLog);


        unset($params['id']);

        if (!isset($params['clue_id']) || empty($params['clue_id'])) {
            throw new ParamException(['msg' => '线索没有ID属性：clue_id', 'errorCode' => 40001, 'code' => 400, 'message' => 'error']);
        }
//
//        if(!isset($params['page_id'])){
//            throw new ParamException(['msg'=>'线索没有落地页属性：page_id','errorCode'=>40001]);
//        }
//
        /*if (!isset($params['city']) || empty($params['city'])) {
            throw new ParamException(['msg' => '线索没有城市属性：city', 'errorCode' => 40001, 'code' => 400, 'message' => 'error']);
        }*/
//
        if (!isset($params['phone']) || empty($params['phone'])) {
            throw new ParamException(['msg' => '线索没有电话属性：phone', 'errorCode' => 40001, 'code' => 400, 'message' => 'error']);
        }

        $params['type'] = $type;

        $isClue = model('clue')->where('clue_id', $params['clue_id'])->find();
        if ($isClue) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索ID已存在', $params);
            throw new ParamException(['msg' => 'API线索接收失败，线索ID已存在', 'errorCode' => 40001, 'code' => 400, 'message' => 'error']);
        }

        $params['pro_id'] = 5;//综合

        //百度
        if ($type == 1) {

            if (!empty($params['city'])) {
                // 百度广告城市处理
                $city_t = explode(' ', $params['city']);

//                if (count($city_t) == 3) {
//                    $params['clue_city'] = $city_t[1];
//                } elseif (count($city_t) == 2) {
//                    $params['clue_city'] = $city_t[1];
//                    if (strpos($params['clue_city'], '区') !== false) {
//                        $params['clue_city'] = $city_t[0];
//                    }
//                } elseif (count($city_t) == 1) {
//                    $params['clue_city'] = $city_t[0];
//                }
//
//                if (strpos($params['clue_city'], '文山') !== false) {
//                    $city = '文山';
//                } elseif (strpos($params['clue_city'], '凉山') !== false) {
//                    $city = '凉山';
//                } elseif (strpos($params['clue_city'], '甘孜') !== false) {
//                    $city = '甘孜';
//                } elseif (strpos($params['clue_city'], '恩施') !== false) {
//                    $city = '恩施';
//                } else {
//                    $city = str_replace('市', '', $params['clue_city'] ?? '');
//                }
//                $city_info = Db::name('city')->where(['type' => 2, 'name' => $city])->find();
                $city_info= $city_info = clue_city_transform($city_t);
                if (!$city_info) {
                    ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '未匹配到广告城市id', $params);
                    $params['err_msg'] = '未匹配到广告城市id';
                } else {
                    $params['clue_city'] = $city_info['pid'] . '-' . $city_info['id'];
                }
            }

            // 拿到表单里的线索名称
            if (isset($params['formDetail']) && !empty($params['formDetail'])) {

                if (is_string($params['formDetail'])) {
                    $params['formDetail'] = json_decode($params['formDetail'],true);
                }
//                $params['formDetail'] = json_decode($params['formDetail'],true);
//                dump($params);die;
                $params['remark'] = json_encode($params['formDetail'], JSON_UNESCAPED_UNICODE);
                $car = [];
                $house = [];
                foreach ($params['formDetail'] as $k => $v) {
                    if ($v['type'] == 'name' || $v['name'] == '称呼') {
                        $params['clue_name'] = $v['value'];
                    }

                    if ($v['type'] == 'city' || $v['name'] == '城市') {

                        // 百度广告城市处理
                        $city_t = explode(' ', $v['value']);

//                        if(strpos($city_t[0], '香港') !== false){
//                            $params['city']='香港';
//                        }elseif (strpos($city_t[0], '澳门') !== false){
//                            $params['city']='澳门';
//                        }elseif (strpos($city_t[0], '台湾') !== false){
//                            $params['city']='台湾';
//                        }else{
//                        if (count($city_t) == 3) {
//                            $params['city'] = $city_t[1];
//                        } elseif (count($city_t) == 2) {
//                            $params['city'] = $city_t[1];
//                            if (strpos($params['city'], '区') !== false) {
//                                $params['city'] = $city_t[0];
//                            }
//                        } elseif (count($city_t) == 1) {
//                            $params['city'] = $city_t[0];
//                        }
//                        }
                    }
                    if (!empty($v['city1']) || !empty($v['city2']) || !empty($v['city3'])  || strpos($v['name'], '所在城市') !== false || strpos($v['name'], '房产所在地') !== false) {
                        // 百度广告城市处理
                        $city_t = explode(' ', $v['value']);

//                        if(strpos($city_t[0], '香港') !== false){
//                            $params['city']='香港';
//                        }elseif (strpos($city_t[0], '澳门') !== false){
//                            $params['city']='澳门';
//                        }elseif (strpos($city_t[0], '台湾') !== false){
//                            $params['city']='台湾';
//                        }else{
//                        if (count($city_t) == 3) {
//                            $params['city'] = $city_t[1];
//                        } elseif (count($city_t) == 2) {
//                            $params['city'] = $city_t[1];
//                            if (strpos($params['city'], '区') !== false) {
//                                $params['city'] = $city_t[0];
//                            }
//                        } elseif (count($city_t) == 1) {
//                            $params['city'] = $city_t[0];
//                        }
//                        }
                    }

                    // 性别
                    if ($v['name'] == '性别' && $v['type'] == 'gender') {
                        if ($params['gender'] == '男') {
                            $params['gender'] = 1;
                        } elseif ($params['gender'] == '女') {
                            $params['gender'] = 2;
                        } else {
                            $params['gender'] = 0;
                        }
                    }

                    // 年龄
                    if ($v['name'] == '年龄' && $v['type'] == 'age') {
                        $params['age'] = $v['value'];
                    }

                    if ($v['name'] == '申请金额' || $v['name'] == '申请额度' || $v['name'] == '贷款额度' || $v['name'] == '借款额度' || $v['name'] == '借款金额' ) {
                        $params['apply_limit'] = $v['value'];
                    }

                    if (strpos($v['name'], '车') !== false) {
                        $car[] = $v['name'] . '：' . $v['value'];
                        $params['pro_id'] = 4;
                    }

                    if (strpos($v['name'], '房') !== false) {
                        $house[] = $v['name'] . '：' . $v['value'];
                        $params['pro_id'] = 3;
                    }

                    $params['car'] = implode('|', $car);
                    $params['house'] = implode('|', $house);
                }
            }

            // 根据广告账户名查广告账户id
//            if(!isset($params['adv_name'])){
//                throw new ParamException(['msg'=>'线索没有投广告账户名属性：adv_name','errorCode'=>40001]);
//            }elseif (!empty($params['adv_name'])){
//                $account = Db::name('account')->where('acc_name',$params['adv_name'])->find();
//            }else{
//                $account = Db::name('account')->where('acc_name',$params['ucName'])->find();
//            }
//            if(!$account){
//                throw new ParamException(['msg'=>'投广告账户名未授权','errorCode'=>40002]);
//            }
//            $params['adv_id'] = $account['adv_id'];
            $params['adv_id'] = $params['ucid'];

        }

        //腾讯
        if ($type == 2) {
            // 性别
            if (isset($params['gender'])) {
                if ($params['gender'] == 'GENDER_TYPE_MALE') {
                    $params['gender'] = 1;
                } elseif ($params['gender'] == 'GENDER_TYPE_FEMALE') {
                    $params['gender'] = 2;
                } else {
                    $params['gender'] = 0;
                }
            }

            // 线索类型
            if (isset($params['clue_type'])) {
                $clue_types = config('clue.clue_types');
                $params['clue_type'] = $clue_types[$params['clue_type']] ?? '未知';
            }

            // 线索来源
            if (isset($params['source'])) {
                $sources = config('clue.sources');
                $params['source'] = $sources[$params['source']] ?? '未知';
            }

            // 腾讯广告城市处理
            if (strpos($params['city'], '|') !== false) {
                $city_t = explode('|', $params['city']);
            } else {
                $city_t = explode('-', $params['city']);
            }
//            if(strpos($city_t[0], '香港') !== false){
//                $params['city']='香港';
//            }elseif (strpos($city_t[0], '澳门') !== false){
//                $params['city']='澳门';
//            }elseif (strpos($city_t[0], '台湾') !== false){
//                $params['city']='台湾';
//            }else{
//            if (count($city_t) == 3) {
//                $params['city'] = $city_t[1];
//            } elseif (count($city_t) == 2) {
//                $params['city'] = $city_t[1];
//                if (strpos($params['city'], '区') !== false) {
//                    $params['city'] = $city_t[0];
//                }
//            } elseif (count($city_t) == 1) {
//                $params['city'] = $city_t[0];
//            }
//            }

            // 腾讯落地页修改
            if (strpos($params['site_url'], "?")) {
                $params['site_url'] = str_replace(substr($params['site_url'], strpos($params['site_url'], "?")), '', $params['site_url']);
            }

            // 表单内容
            if (isset($params['bundle'])) {
                $car = [];
                $house = [];
                $bundle = json_decode($params['bundle'], true);
                unset($bundle['表单名称']);
                $params['remark'] = json_encode($params['bundle'], JSON_UNESCAPED_UNICODE);

                foreach ($bundle as $k => $v) {
                    if ($k == '申请金额' || $k == '申请额度' || $k == '贷款额度' ||$k == '借款额度' || $k == '所需额度'||$k=='需求金额'|| $k == '借款金额') {
                        $params['apply_limit'] = $v;
                    }

                    if (strpos($k, '车') !== false) {
                        $car[] = $k . '：' . $v;
                        $params['pro_id'] = 4;
                    }

                    if (strpos($k, '房') !== false) {
                        $house[] = $k . '：' . $v;
                        $params['pro_id'] = 3;
                    }

                }
                $params['car'] = implode('|', $car);
                $params['house'] = implode('|', $house);
            }

        }

        if ($type == 3) {

            if (!empty($params['location'])) {
                // 百度广告城市处理
                $city_t = explode('+', $params['location']);

//                if (count($city_t) == 3) {
//                    $params['clue_city'] = $city_t[1];
//                } elseif (count($city_t) == 2) {
//                    $params['clue_city'] = $city_t[1];
//                    if (strpos($params['clue_city'], '区') !== false) {
//                        $params['clue_city'] = $city_t[0];
//                    }
//                } elseif (count($city_t) == 1) {
//                    $params['clue_city'] = $city_t[0];
//                }
//
//                if (strpos($params['clue_city'], '文山') !== false) {
//                    $city = '文山';
//                } elseif (strpos($params['clue_city'], '凉山') !== false) {
//                    $city = '凉山';
//                } elseif (strpos($params['clue_city'], '甘孜') !== false) {
//                    $city = '甘孜';
//                } elseif (strpos($params['clue_city'], '恩施') !== false) {
//                    $city = '恩施';
//                } else {
//                    $city = str_replace('市', '', $params['clue_city'] ?? '');
//                }
//                $city_info = Db::name('city')->where(['type' => 2, 'name' => $city])->find();
                $city_info = clue_city_transform($city_t);
                if (!$city_info) {
                    ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '未匹配到广告城市id', $params);
                    $params['err_msg'] = '未匹配到广告城市id';
                } else {
                    $params['clue_city'] = $city_info['pid'] . '-' . $city_info['id'];
                }
            }

            $city_t=[$params['city']];

            // 性别
            if (isset($params['gender'])) {
                if ($params['gender'] == '男') {
                    $params['gender'] = 1;
                } elseif ($params['gender'] == '女') {
                    $params['gender'] = 2;
                } else {
                    $params['gender'] = 0;
                }
            }

            // 橙子建战落地页修改
//            if(strpos($params['site_url'],"&q=")){
//                $params['site_url'] = str_replace(substr($params['site_url'], strpos($params['site_url'],"&q=")), '', $params['site_url']);
//            }
            $params['page_id']=$params['site_id'];

            // 表单内容
            $params['pro_id'] = 5;
            if (isset($params['remark_dict'])) {
                $car = [];
                $house = [];
                foreach ($params['remark_dict'] as $k => $v) {

                    if ($k == '申请金额' || $k == '申请额度' || $k == '贷款额度' || $k=='借款额度'|| $k == '所需额度'||$k=='需求金额'|| $k == '借款金额') {
                        $params['apply_limit'] = $v;
                    }

                    if (strpos($k, '车') !== false) {
                        $car[] = $k . '：' . $v;
                        $params['pro_id'] = 4;
                    }

                    if (strpos($k, '房') !== false) {
                        $house[] = $k . '：' . $v;
                        $params['pro_id'] = 3;
                    }
                }
                $params['remark'] = json_encode($params['remark_dict'], JSON_UNESCAPED_UNICODE);
                $params['car'] = implode('|', $car);
                $params['house'] = implode('|', $house);
            }

        }



        $isDayPhone = model('clue')->where(['phone' => $params['phone']])->whereTime('create_time','d')->find();
        if (!empty($isDayPhone)) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索已存在', $post);
            throw new ParamException(['msg' => '线索已存在', 'errorCode' => 40001, 'code' => 400, 'message' => 'error']);
        }

        $params['ip'] = isset($params['ip']) ? $params['ip'] : get_client_ip();
//        if (strpos($params['city'], '文山') !== false) {
//            $city = '文山';
//        } elseif (strpos($params['city'], '凉山') !== false) {
//            $city = '凉山';
//        } elseif (strpos($params['city'], '甘孜') !== false) {
//            $city = '甘孜';
//        } elseif (strpos($params['city'], '恩施') !== false) {
//            $city = '恩施';
//        } else {
//            $city = str_replace('市', '', $params['city'] ?? '');
//        }
//        $city_info = Db::name('city')->where(['type' => 2, 'name' => $city])->find();
        $city_info= $city_info = clue_city_transform($city_t);
        if (!$city_info) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '未匹配到城市id', $params);
//            throw new ParamException(['msg'=>'线索接收失败，线索没有城市属性','errorCode'=>40001]);
            $params['city'] = '';
            $params['err_msg'] = '未匹配到城市id城市解析失败';
        } else {
            $province = Db::name('city')->where(['id' => $city_info['pid']])->find();
            $params['city'] = $province['id'] . '-' . $city_info['id'];
        }

        //记录线索成本
        $isAid = Db::name('account')->where('adv_id', $params['adv_id'])->find();

        //城市是否禁用
        $isCity=model('accountCity')->where(['acc_id'=>$isAid['id'],'city'=>$params['city'],'status'=>1])->find();
        if(!empty($isCity)){
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市已禁用', $post);
            //throw new ParamException(['msg' => '账户城市已禁用', 'errorCode' => 40001, 'code' => 400, 'message' => 'error']);
            throw new ParamException(['msg' => '线索已存在', 'errorCode' => 40001, 'code' => 400, 'message' => 'error']);
        }


        if(!empty($isAid)){
            if($isAid['status']!=1){
                ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户已禁用', $params);
                throw new ParamException(['msg' => '账户已禁用', 'errorCode' => 40001, 'code' => 400, 'message' => 'error']);
            }

            $clueCost = model('ClueAddCost')->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => $params['city']])
                ->where('status', 1)
                ->find();
            if (empty($clueCost)) {
                // 找不到城市就找默认全国城市
                $clueCost = model('ClueAddCost')
                    ->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => ""])
                    ->where('status', 1)
                    ->find();
            }
            if (!empty($clueCost)) {
                $params['price']=$clueCost['money'];
                $params['true_price']=$clueCost['money'];
                $params['xz_price']=$clueCost['money'];
                $params['xz_true_price']=$clueCost['money'];
                $params['xz_price2']=$clueCost['money'];
                $params['xz_true_price2']=$clueCost['money'];
            }else{
                $params['price']=$isAid['clue_cost'];
                $params['true_price']=$isAid['clue_cost'];
                $params['xz_price']=$isAid['clue_cost'];
                $params['xz_true_price']=$isAid['clue_cost'];
                $params['xz_price2']=$isAid['clue_cost'];
                $params['xz_true_price2']=$isAid['clue_cost'];
            }
        }
        $params['account_id']=$isAid['id'];
        //判断线索重复
        $isClue = model('clue')->where(['phone' => $params['phone']])->find();
        // 1.记录线索
        $clueModel = new \app\common\model\Clue();
        $res = $clueModel->saveData($params);
        $id = $clueModel->id;

        if ($res['code'] != 1000) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索接收失败', $post);
            throw new ParamException(['msg' => '线索接收失败', 'errorCode' => 40001, 'code' => 400, 'message' => 'error']);
        }
        Db::name('clue_api_log')->where('id',$apiId)->update(['status'=>1]);

        if ($isClue) {
            Db::name('clue_err_log')->insert(['type' => 1,'phone'=>$params['phone'], 'clue_id' => $id, 'adv_id' => $params['adv_id'], 'pro_id' => $params['pro_id'], 'city' => $params['city'], 'create_time' => time()]);
        }

        if (empty($params['city'])&&empty($params['clue_city'])) {
            return Json(['code' => 200, 'msg' => '线索接收成功,城市匹配失败：' . json_encode($res, JSON_UNESCAPED_UNICODE), 'message' => 'success']);
        }

        // 2.推送线索
//        $clue_info = $clueModel->find($id);
//        $res = $this->cluePush($clue_info, true);

        $jobHandlerClassName  = 'app\job\ExprotClue@fire';
        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
        $jobQueueName     = "ExprotClue";

        $jobData = ['id'=>$id];

        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);

        return Json(['code' => 200, 'msg' => '线索接收成功', 'message' => 'success']);
    }

    public function ClueCostLog(){

        $start = strtotime("2024-04-01");
        for ($i = 0; $i < 25; $i++) {
            $time = date("Y-m-d", strtotime("+{$i} day", $start));

            $timeStar = strtotime($time . ' 00:00:00');
            $timeEnd = strtotime($time . ' 23:59:59');
            $list = model('Clue')
                ->alias('a')
                ->field('a.adv_id,pro_id,city,count(id) num,sum(price) price')
                ->where(['create_time' => ['between', [$timeStar, $timeEnd]]])
                ->where('price', '>', 0)
                ->where('adv_id', 9521)
                ->where('is_create_cost', 0) // 未生成消耗成本的
                ->group('a.adv_id,pro_id,city')
                ->select();

            $insertData = [];
            foreach ($list as $v) {
                $account = Db::name('account')->where('adv_id', $v['adv_id'])->find();
                $clueNum = $v['num'];
                $trueCost1 = bcdiv($v['price'], bcadd(1, $account['clue_rate'] / 100, 4), 3);
                if ($clueNum > 0) {
                    $trueCost2 = bcdiv($trueCost1, $clueNum, 3);
                    $changeCost = bcdiv($v['price'], $clueNum, 3);
                } else {
                    $trueCost2 = 0;
                    $changeCost = 0;
                }

                $insertData[] = [
                    'account_id' => $account['id'],
                    'pro_id' => $v['pro_id'],
                    'time' => $time,
                    'city' => $v['city'],
                    'exposure_val' => 0,
                    'click_val' => 0,
                    'money' => $v['price'],
                    'transform_val' => $clueNum,
                    'remark' => '',
                    'clue_num' => $clueNum,
                    'change_cost' => $changeCost,
                    'true_cost' => $trueCost2,
                    'true_consume' => $trueCost1,
                    'create_time' => time(),
                    'type' => 2,
                ];
            }

            if (!empty($insertData)) {
                Db::startTrans();
                try {

                    model('ClueCostLog')->insertAll($insertData);

                    Db::commit();
                    echo $time . '插入成功';
                } catch (\think\Exception $e) {
                    Db::rollback();
                    echo $time . '插入失败';
                }
            }
        }
    }

    public function ClueCostLog2()
    {
        $all_price = 3854;
        $adv_id = 9515; //账号
        $start_date = "2024-05-06";
        $end_date = "2024-05-12";

        $start_time = strtotime($start_date);
        $end_time = strtotime($end_date . ' 23:59:59');
        $clue_num = model('Clue')
            ->where(['create_time' => ['between', [$start_time, $end_time]]])
            ->where('adv_id', $adv_id)
            ->count();

        $one_price = bcdiv($all_price, $clue_num, 2); //成本价格
        for ($i = 0; $i < 7; $i++) {
            $time = date("Y-m-d", strtotime("+{$i} day", $start_time));

            $timeStar = strtotime($time . ' 00:00:00');
            $timeEnd = strtotime($time . ' 23:59:59');
            $list = model('Clue')
                ->alias('a')
                ->field('a.adv_id,pro_id,city,count(id) num,sum(price) price')
                ->where(['create_time' => ['between', [$timeStar, $timeEnd]]])
                ->where('adv_id', $adv_id)
                ->group('a.adv_id,pro_id,city')
                ->select();

            $insertData = [];
            foreach ($list as $v) {
                $account = Db::name('account')->where('adv_id', $v['adv_id'])->find();
                $clueNum = $v['num'];
                $price = bcmul($one_price, $clueNum, 3);
                $trueCost1 = bcdiv($price, bcadd(1, $account['clue_rate'] / 100, 4), 3);
                if ($clueNum > 0) {
                    $trueCost2 = bcdiv($trueCost1, $clueNum, 3);
                    $changeCost = bcdiv($price, $clueNum, 3);
                } else {
                    $trueCost2 = 0;
                    $changeCost = 0;
                }

                $insertData[] = [
                    'account_id' => $account['id'],
                    'pro_id' => $v['pro_id'],
                    'time' => $time,
                    'city' => $v['city'],
                    'exposure_val' => 0,
                    'click_val' => 0,
                    'money' => $price,
                    'transform_val' => $clueNum,
                    'remark' => '',
                    'clue_num' => $clueNum,
                    'change_cost' => $changeCost,
                    'true_cost' => $trueCost2,
                    'true_consume' => $trueCost1,
                    'create_time' => time(),
                    'type' => 2,
                ];
            }

            if (!empty($insertData)) {
                Db::startTrans();
                try {

                    model('ClueCostLog')->insertAll($insertData);

                    Db::commit();
                    echo $time . '插入成功';
                } catch (\think\Exception $e) {
                    Db::rollback();
                    echo $time . '插入失败';
                }
            }
        }
    }

}